import { ExceptionFilter, Catch, ArgumentsHost, HttpException, Logger } from '@nestjs/common';
import { Request, Response } from 'express';
import R from '../dto/R.dto';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  private readonly logger = new Logger(HttpExceptionFilter.name);

  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();
    const message = exception.message;

    // 记录错误日志
    this.logger.error(
      `路径: ${request.url} - 方法: ${request.method} - IP: ${request.ip} - 状态: ${status} - 信息: ${message}`,
    );

    // 使用统一的响应格式
    const responseBody = R.fail(message);

    response.status(status).json(responseBody);
  }
}